package jwtconfig

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// MyPayload 定义负载继承jwt的标准负载
type MyPayload struct {
	Username string
	jwt.StandardClaims
}

// 定义secret签名
var signatureKey []byte = []byte("!@#qwe")

// MakeUserToken 生成加密token
func MakeUserToken(user string) string {
	//传入用户信息生成负载实例
	payload := MyPayload{
		Username: user,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() + 10,
			//过期时间
			ExpiresAt: time.Now().Add(1 * time.Hour).Unix(),
		},
	}

	//生成加密Signature
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, payload).SignedString(signatureKey)
	if err != nil {
		fmt.Println("生成token失败", err)
	}
	return token
}

// 解密token
func ParserUserToken(token string) (*MyPayload, error) {
	//解密后jwt.Token对象，从该对象可以获取Header，Payload，Signature（claims）等信息
	unsafeToken, err1 := jwt.ParseWithClaims(token, &MyPayload{}, func(token *jwt.Token) (interface{}, error) {
		return signatureKey, nil
	})

	//将负载转化为结构体
	claims, ok := unsafeToken.Claims.(*MyPayload)

	if ok && unsafeToken.Valid {
		return claims, nil
	} else {
		return claims, err1
	}

	/*
		//验证token是否有效
		if unsafeToken.Valid {
			//错误判断并返回错误信息
			if err1 != nil {
				return "未携带有效token", unsafeToken.Claims
			} else if ve, ok := err1.(*jwt.ValidationError); ok {
				if ve.Errors&jwt.ValidationErrorMalformed != 0 {
					return "无效token", nil
				} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
					return "token已过期", nil
				} else {
					return "", nil
				}
			}
		}
	*/

}
